package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * OrderService
 *
 * @author liudo
 * @version 1.0
 * @project sky-take-out
 * @date 2023/12/12 09:21:37
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final AddressBookMapper addressBookMapper;
    private final ShoppingCartMapper shoppingCartMapper;
    private final OrderMapper orderMapper;
    private final OrderDetailMapper orderDetailMapper;
    private final WebSocketServer webSocketServer;
    private final UserMapper userMapper;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 1.地址是否存在
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (Objects.isNull(addressBook)) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 2. 核心代码
        // 2.1 谁有啥东西 - 查询购物车详情
        ShoppingCart shoppingCartQuery = new ShoppingCart();
        shoppingCartQuery.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectList(shoppingCartQuery);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 2.2 生成订单 - 主键返回
        Orders orders = new Orders();
        // 订单号 - 业务ID 唯一性 一般是要有意义的 地区号 + 时间 + 店铺号
        long currentTimeMillis = System.currentTimeMillis();
        orders.setNumber(String.valueOf(currentTimeMillis));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setAddressBookId(ordersSubmitDTO.getAddressBookId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayMethod(1);
        orders.setPayStatus(Orders.UN_PAID);
        // todo 总金额 - 前端不可信 - 稍后自己算
        // 总金额 = 所有详情之和
        // 普通
        // BigDecimal decimal = new BigDecimal(0);
        // for (ShoppingCart shoppingCart : shoppingCartList) {
        //     BigDecimal multiply = shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber()));
        //     decimal = decimal.add(multiply);
        // }
        // Steam流 [shoppingCard ] -- [总价 ] -- > 总价的总价
        BigDecimal init = new BigDecimal(0);
        init = init.add(new BigDecimal(6));
        init = init.add(new BigDecimal(ordersSubmitDTO.getPackAmount()));
        // [1,2,35,32,32,45,23,3]
        BigDecimal decimal = shoppingCartList.stream()
                .map(shoppingCart -> shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())))
                .reduce(init, BigDecimal::add);

        orders.setAmount(decimal);
        orders.setRemark(ordersSubmitDTO.getRemark());
        orders.setUserName(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        // 地址 省市区+详情
        String address = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        orders.setAddress(address);
        orders.setConsignee(addressBook.getConsignee());
        orders.setEstimatedDeliveryTime(ordersSubmitDTO.getEstimatedDeliveryTime());
        orders.setDeliveryStatus(ordersSubmitDTO.getDeliveryStatus());
        orders.setPackAmount(ordersSubmitDTO.getPackAmount());
        orders.setTablewareNumber(ordersSubmitDTO.getTablewareNumber());
        orders.setTablewareStatus(ordersSubmitDTO.getTablewareStatus());

        orderMapper.insert(orders);
        // 2.3 生成订单详情 - 订单ID - 一对多 [ShoppingCard， ShoppingCard， ShoppingCard] --> [OrderDetail, OrderDetail, OrderDetail]
        List<OrderDetail> orderDetailList = shoppingCartList.stream()
                .map(shoppingCart -> {
                    OrderDetail orderDetail = new OrderDetail();
                    BeanUtils.copyProperties(shoppingCart, orderDetail);
                    // 最核心的 - 订单ID
                    orderDetail.setOrderId(orders.getId());
                    return orderDetail;
                })
                .collect(Collectors.toList());
        orderDetailMapper.insertBatch(orderDetailList);
        // 2.4 清空购物车
        shoppingCartMapper.delete(shoppingCartQuery);
        // 3. 结果封装
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        return orderSubmitVO;
    }

    @Override
    public void paySuccess(String number) {
        // 订单状态改成已支付
        Orders ordersQuery = new Orders();
        ordersQuery.setNumber(number);
        Orders orders = orderMapper.selectOne(ordersQuery);

        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayStatus(Orders.PAID);
        orderMapper.updateById(orders);

        // 给浏览器发消息，通知来单了
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 1);
        jsonObject.put("orderId", orders.getId());
        jsonObject.put("content", orders.getNumber());

        webSocketServer.sendToAllClient(jsonObject.toJSONString());
    }

    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Orders orders = new Orders();
        orders.setStatus(ordersPageQueryDTO.getStatus());
        orders.setUserId(BaseContext.getCurrentId());
        Page<Orders> page = orderMapper.selectPage(orders);
        List<Orders> ordersList = page.getResult();

        List<OrderVO> orderVOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ordersList)) {
            List<Long> orderIds = ordersList.stream().map(Orders::getId).collect(Collectors.toList());
            List<OrderDetail> orderDetailList = orderDetailMapper.selectListByOrderIds(orderIds);

            orderVOS = ordersList.stream().map(item -> {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(item, orderVO);
                List<OrderDetail> orderDetails = orderDetailList.stream()
                        .filter(orderDetail -> Objects.equals(orderDetail.getOrderId(), item.getId()))
                        .collect(Collectors.toList());
                orderVO.setOrderDetailList(orderDetails);
                return orderVO;
            }).collect(Collectors.toList());
        }
        return new PageResult(page.getTotal(), orderVOS);
    }

    @Override
    public OrderVO orderDetail(Long id) {
        Orders orders = orderMapper.selectById(id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectListByOrderIds(Collections.singletonList(id));
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    @Override
    public void cancelById(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setPayStatus(2);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.updateById(orders);
    }

    @Override
    public void repetition(Long id) {
        List<OrderDetail> orderDetailList = orderDetailMapper.selectListByOrderIds(Collections.singletonList(id));
        List<ShoppingCart> shoppingCarts = orderDetailList.stream()
                .map(orderDetail -> {
                    ShoppingCart shoppingCart = new ShoppingCart();
                    BeanUtils.copyProperties(orderDetail, shoppingCart);
                    shoppingCart.setUserId(BaseContext.getCurrentId());
                    shoppingCart.setCreateTime(LocalDateTime.now());
                    return shoppingCart;
                }).collect(Collectors.toList());
        shoppingCartMapper.insertBatch(shoppingCarts);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersPageQueryDTO, orders);
        Page<Orders> page = orderMapper.selectPage(orders);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public OrderStatisticsVO statistics() {
        return orderMapper.selectStatistics();
    }

    @Override
    public OrderVO detailsById(Long id) {
        return getOrderVO(id);
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.updateById(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        orders.setId(ordersRejectionDTO.getId());
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.updateById(orders);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setStatus(Orders.CANCELLED);
        orderMapper.updateById(orders);
    }

    @Override
    public void deliveryById(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.updateById(orders);
    }

    @Override
    public void completeById(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orderMapper.updateById(orders);
    }

    @Override
    public void reminder(Long id) {
        // 校验
        Orders orders = orderMapper.selectById(id);
        if (Objects.isNull(orders)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 2);
        jsonObject.put("orderId", orders.getId());
        jsonObject.put("content", orders.getNumber());
        webSocketServer.sendToAllClient(jsonObject.toJSONString());
    }

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<Map<String, Object>> mapList = orderMapper.selectTurnoverStatistics(begin, end);
        // [{}, {}, {}, {}] ----> [''，''，''，''],  --- ''，''，''，''
        String dateList = mapList.stream()
                .map(item -> (String) item.get("day"))
                .collect(Collectors.joining(","));
        // [{}, {}, {}, {}] ----> [BigDecimal，BigDecimal，BigDecimal，BigDecimal],  --- ''，''，''，''
        String turnoverList = mapList.stream()
                .map(item -> (BigDecimal) item.get("turnover"))
                .map(BigDecimal::toString)
                .collect(Collectors.joining(","));

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        // 逗号分隔
        turnoverReportVO.setDateList(dateList);
        turnoverReportVO.setTurnoverList(turnoverList);
        return turnoverReportVO;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 时间列表的问题
        ArrayList<LocalDate> localDates = getLocalDates(begin, end);
        // 把时间列表作为参数 进行SQL查询
        List<Map<String, Object>> mapList = userMapper.selectUserStatistics(localDates);
        // 数据处理
        String dateList = mapList.stream()
                .map(item -> (String) item.get("day"))
                .collect(Collectors.joining(","));
        String totalUserList = mapList.stream()
                .map(item -> (Long) item.get("all_count"))
                .map(String::valueOf)
                .collect(Collectors.joining(","));
        String newUserList = mapList.stream()
                .map(item -> (Long) item.get("user_count"))
                .map(String::valueOf)
                .collect(Collectors.joining(","));
        // 结果封装
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(dateList);
        userReportVO.setTotalUserList(totalUserList);
        userReportVO.setNewUserList(newUserList);
        return userReportVO;
    }

    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        // 折线图数据
        ArrayList<LocalDate> localDates = getLocalDates(begin, end);
        List<Map<String, Object>> mapList = orderMapper.selectOrderStatistics2(localDates);
        String dateList = mapList.stream()
                .map(item -> (String) item.get("day"))
                .collect(Collectors.joining(","));
        String orderCountList = mapList.stream()
                .map(item -> (Long) item.get("total_number"))
                .map(String::valueOf)
                .collect(Collectors.joining(","));
        String validOrderCountList = mapList.stream()
                .map(item -> (Long) item.get("number_valid_orders"))
                .map(String::valueOf)
                .collect(Collectors.joining(","));
        // 数值部分
        Map<String, Object> map = orderMapper.selectOrderStatistics(begin, end);
        Long totalNumber = (Long) map.get("total_number");
        Long numberValidOrders = (Long) map.get("number_valid_orders");
        BigDecimal orderCompletionRate = (BigDecimal) map.get("order_completion_rate");

        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(dateList);
        orderReportVO.setOrderCountList(orderCountList);
        orderReportVO.setValidOrderCountList(validOrderCountList);
        orderReportVO.setTotalOrderCount(totalNumber.intValue());
        orderReportVO.setValidOrderCount(numberValidOrders.intValue());
        orderReportVO.setOrderCompletionRate(orderCompletionRate.doubleValue());
        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        List<Map<String, Object>> mapList = orderDetailMapper.selectTop10(begin, end);
        String nameList = mapList.stream()
                .map(item -> (String) item.get("name"))
                .collect(Collectors.joining(","));
        String numberList = mapList.stream()
                .map(item -> (Long) item.get("count"))
                .map(String::valueOf)
                .collect(Collectors.joining(","));

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(nameList);
        salesTop10ReportVO.setNumberList(numberList);
        return salesTop10ReportVO;
    }

    @Override
    public void export(HttpServletResponse httpServletResponse) {
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/operationalDataReportTemplate.xlsx");
            if (Objects.isNull(inputStream)) {
                throw new RuntimeException();
            }
            // 读取Excel到内存中
            Workbook wb = WorkbookFactory.create(inputStream);
            // 31天前~昨天
            LocalDate now = LocalDate.now();
            LocalDate yesterday = now.minusDays(1L);
            LocalDate daysAgo30 = yesterday.minusDays(29L);
            Map<String, Object> map = orderMapper.selectStatisticalResults(daysAgo30, yesterday);
            // 营业额
            BigDecimal amount = (BigDecimal) map.get("amount");
            // 订单完成率
            BigDecimal orderCompletionRate = (BigDecimal) map.get("order_completion_rate");
            // 新增用户数
            Long numberNewUsers = (Long) map.get("number_new_users");
            // 有效订单
            Long numberValidOrders = (Long) map.get("number_valid_orders");
            // 平均客单价
            BigDecimal customerUnitPrice = (BigDecimal) map.get("customer_unit_price");

            Sheet sheetAt = wb.getSheetAt(0);
            Row row2 = sheetAt.getRow(1);
            Row row4 = sheetAt.getRow(3);
            Row row5 = sheetAt.getRow(4);

            Cell cell22 = row2.getCell(1);
            Cell cell43 = row4.getCell(2);
            Cell cell53 = row5.getCell(2);
            Cell cell45 = row4.getCell(4);
            Cell cell55 = row5.getCell(4);
            Cell cell47 = row4.getCell(6);

            cell22.setCellValue("苍穹外卖订单数据导出:" + yesterday + "~" + daysAgo30);
            cell43.setCellValue(amount.doubleValue());
            cell45.setCellValue(orderCompletionRate.doubleValue());
            cell47.setCellValue(numberNewUsers);
            cell53.setCellValue(numberValidOrders);
            cell55.setCellValue(customerUnitPrice.doubleValue());
            // 数据列表
            ArrayList<LocalDate> localDates = getLocalDates(daysAgo30, yesterday);

            List<Map<String, Object>> mapList = orderMapper.selectStatisticalResults2(localDates);
            // 循环渲染数据
            for (int i = 7; i <= 36; i++) {
                int index = i - 7;
                Map<String, Object> objectMap = mapList.get(index);

                Row row = sheetAt.getRow(i);

                Cell cell2 = row.getCell(1);
                Cell cell3 = row.getCell(2);
                Cell cell4 = row.getCell(3);
                Cell cell5 = row.getCell(4);
                Cell cell6 = row.getCell(5);
                Cell cell7 = row.getCell(6);

                String day = (String) objectMap.get("day");
                BigDecimal amount1 = (BigDecimal) objectMap.get("amount");
                Long numberValidOrders1 = (Long) objectMap.get("number_valid_orders");
                BigDecimal orderCompletionRate1 = (BigDecimal) objectMap.get("order_completion_rate");
                BigDecimal customerUnitPrice1 = (BigDecimal) objectMap.get("customer_unit_price");
                Long numberNewUsers1 = (Long) objectMap.get("number_new_users");

                cell2.setCellValue(day);
                cell3.setCellValue(amount1.doubleValue());
                cell4.setCellValue(numberValidOrders1);
                cell5.setCellValue(orderCompletionRate1.doubleValue());
                cell6.setCellValue(customerUnitPrice1.doubleValue());
                cell7.setCellValue(numberNewUsers1);
            }

            // 设置响应头
            httpServletResponse.reset();
            httpServletResponse.setContentType("application/vnd.ms-excel");
            httpServletResponse.setCharacterEncoding("utf-8");
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            // 将文件写入输出流
            wb.write(outputStream);
            // 关闭
            wb.close();
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private OrderVO getOrderVO(Long id) {
        Orders orders = orderMapper.selectById(id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectListByOrderIds(Collections.singletonList(id));
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 获取本地日期
     *
     * @param begin 开始
     * @param end   终止
     * @return {@link ArrayList}<{@link LocalDate}>
     */
    private static ArrayList<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        while (true) {
            begin = begin.plusDays(1L);
            if (begin.isAfter(end)) {
                break;
            }
            localDates.add(begin);
        }
        return localDates;
    }
}
